package com.alks.common.config.handler;

import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.TextAlignment;

public class TextFooterEventHandler implements IEventHandler {

    private final PdfFont pdfFont;

    protected int page;

    public TextFooterEventHandler(PdfFont pdfFont) {
        this.pdfFont = pdfFont;
    }

    public void handleEvent(Event event) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfPage page = docEvent.getPage();
        Rectangle pageSize = page.getPageSize();
        PdfCanvas pdfCanvas = new PdfCanvas(page);
        Canvas canvas = new Canvas(pdfCanvas, Rectangle.getRectangleOnRotatedPage(pageSize, page));
        ++this.page;

        float x = (pageSize.getLeft() + pageSize.getRight()) / 2;
        float y = pageSize.getBottom() + 15;

        Paragraph footer = new Paragraph("第 - " +this.page+ " - 页").setFontSize(12).setFont(pdfFont);
        canvas.showTextAligned(footer, x, y, TextAlignment.CENTER);
        canvas.close();
    }
}